package com.lyc.service.impl;

import com.lyc.DTO.UserDTO;
import com.lyc.DTO.AdminUserDTO;
import com.lyc.mapper.UserMapper;
import com.lyc.service.UserService;
import com.lyc.utils.JwtUtil;
import com.lyc.utils.Md5Util;
import com.lyc.pojo.User;
import com.lyc.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    // 注入PostService
    @Autowired
    private com.lyc.service.PostService postService;

    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    // 注册
    @Override
    public void register(String username, String password, String avatar) {
        if (username == null || password == null) {
            throw new IllegalArgumentException("用户名或密码不能为空");
        }

        // 添加日志确认参数
        System.out.println("Service received username: " + username);
        System.out.println("Service received password: " + password);

        //加密
        String md5String = Md5Util.getMD5String(password);

        //添加
        userMapper.add(username,md5String,avatar);

    }

    // 获取用户帖子数量
    @Override
    public Integer getPostCount(Integer userId) {
        return userMapper.getPostCount(userId);
    }

    // 通过id查询用户
    @Override
    public User findById(Integer userId) {
         return userMapper.findById(userId);
    }

    //修改用户头像
    @Override
    public void updateAvatar(String avatar) {
        //获取当前用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        System.out.println("当前用于id" + id);
        userMapper.updateAvatar(avatar, id);
    }

    // 修改用户信息
    @Override
    public void updateById(UserDTO userDTO) {
        // 将DTO对象转换为User对象
        User user = new User();
        // 将DTO属性复制到User对象中
        BeanUtils.copyProperties(userDTO, user);
        // 获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        user.setId(id);
        userMapper.updateById(user);
    }
    
    // 管理员修改用户信息
    @Override
    public void updateUserInfoByAdmin(AdminUserDTO adminUserDTO) throws Exception {
        // 检查用户名是否已被其他用户使用
        User existingUser = userMapper.findByUserName(adminUserDTO.getUsername());
        if (existingUser != null && !existingUser.getId().equals(adminUserDTO.getId())) {
            throw new Exception("用户名 '" + adminUserDTO.getUsername() + "' 已被其他用户使用");
        }
        
        // 将DTO对象转换为User对象
        User user = new User();
        // 将DTO属性复制到User对象中
        BeanUtils.copyProperties(adminUserDTO, user);
        
        // 如果密码不为空，则进行加密处理
        if (adminUserDTO.getPassword() != null && !adminUserDTO.getPassword().isEmpty()) {
            String encryptedPassword = Md5Util.getMD5String(adminUserDTO.getPassword());
            user.setPassword(encryptedPassword);
        }
        
        // 不更新用户头像
        userMapper.updateUserInfoByAdmin(user);
    }
    
    // 获取全部用户列表
    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }
    
    // 批量更新用户状态
    @Override
    public void batchUpdateUserStatus(List<Integer> userIds, String status) {
        for (Integer userId : userIds) {
            User user = new User();
            user.setId(userId);
            user.setStatus(status);
            userMapper.updateUserStatus(user);
        }
    }
    
    // 批量更新用户角色
    @Override
    public void batchUpdateUserRole(List<Integer> userIds, String role) {
        for (Integer userId : userIds) {
            User user = new User();
            user.setId(userId);
            user.setRole(role);
            userMapper.updateUserRole(user);
        }
    }
    
    // 批量更新用户认证状态
    @Override
    public void batchUpdateUserVerification(List<Integer> userIds, Boolean isVerified) {
        for (Integer userId : userIds) {
            User user = new User();
            user.setId(userId);
            user.setIsVerified(isVerified);
            userMapper.updateUserVerification(user);
        }
    }
    
    // 删除用户（支持批量删除）
    @Override
    public void deleteUsers(List<Integer> userIds) {
        for (Integer userId : userIds) {
            deleteUserAndRelatedData(userId);
        }
    }
    
    // 删除用户及其相关数据（帖子、评论等）
    @Override
    public void deleteUserAndRelatedData(Integer userId) {
        // 1. 删除用户发布的帖子相关数据
        postService.deletePostsByUserId(userId);
        
        // 2. 删除用户
        userMapper.deleteUserById(userId);
    }
}